import os
import sys

class SlurmScript(object):
    script_body = '''#!/bin/bash
#SBATCH -A belle
#SBATCH -t {bcat_duration}
#SBATCH -N {bcat_nnodes}
#SBATCH -o {bcat_stdout}
#SBATCH -e {bcat_stderr}
#SBATCH -J {bcat_job_name}

source $HOME/belle/belle_custom_setup.sh
source $HOME/belle/belle_general_setup.sh

date
{0}
date
'''

    def __init__(self, name, command_line, opts):
        self.name = name

        if opts.bcat_stdoutdir is None:
            if 'JOB_STDOUT' not in os.environ:
                opts.bcat_stdoutdir = os.getcwd()
            elif not os.access(os.environ['JOB_STDOUT'], os.R_OK | os.W_OK):
                sys.stderr.write("Error accessing `$JOB_STDOUT={0}'; ".format(os.environ['JOB_STDOUT']))
                sys.stderr.write("path does not exist or is not writeable.")
                sys.stderr.write("Continuing using current working directory...")
                
                opts.bcat_stdoutdir = os.getcwd()
            else:
                opts.bcat_stdoutdir = os.environ['JOB_STDOUT']


                
        if opts.bcat_stderrdir is None:
            if 'JOB_STDERR' not in os.environ:
                opts.bcat_stderrdir = os.getcwd()
            elif not os.access(os.environ['JOB_STDERR'], os.R_OK | os.W_OK):
                sys.stderr.write("Error accessing `$JOB_STDERR={0}'; ".format(os.environ['JOB_STDERR']))
                sys.stderr.write("path does not exist or is not writeable.")
                sys.stderr.write("Continuing using current working directory...")
                
                opts.bcat_stderrdir = os.getcwd()
            else:
                opts.bcat_stderrdir = os.environ['JOB_STDERR']

        if opts.bcat_job_name is None:
            opts.bcat_job_name = self.name
                
        if opts.bcat_stdout is None:
            opts.bcat_stdout = os.path.join(opts.bcat_stderrdir, '{0}_%j.out'.format(opts.bcat_job_name))
        
        if opts.bcat_stderr is None:
            opts.bcat_stderr = os.path.join(opts.bcat_stderrdir, '{0}_%j.err'.format(opts.bcat_job_name))

        self.script = SlurmScript.script_body.format(command_line, **vars(opts))

    def __str__(self):
        return self.script
